<template>
  <div>
    <div class="search">
      <input type="text" placeholder="输入城市或拼音" v-model="keyword">
    </div>
    <div class="wrapper" ref="wrapper" v-show="keyword">
      <ul class="result">
        <li
          v-for="(item,index) of this.result"
          :key="index"
          @click="handleClick(item)"
        >{{item.name}}</li>
        <li v-show="!(this.result[0])" class="none">搜索不到该城市</li>
      </ul>
    </div>
  </div>
</template>
<script>
import BScroll from "better-scroll";
export default {
  name: "CitySearch",
  data() {
    return {
      keyword: "",
      result: []
    };
  },
  props: ["cities"],
  mounted() {
    this.$nextTick(() => {
      this.scroll = new BScroll(this.$refs.wrapper, {});
    });
  },
  watch: {
    keyword() {
      var result = [];
      if (this.keyword) {
        for (let k in this.cities) {
          this.cities[k].forEach(ele => {
            if (
              ele.name.startsWith(this.keyword) ||
              ele.spell.startsWith(this.keyword)
            ) {
              result.push(ele);
            }
          });
          this.result = result;
        }
      } else {
        this.result = [];
      }
    }
  },
  methods: {
    handleClick(item) {
      var city = item.name;
      this.$store.commit("changeCity", city);
      this.$router.push("/");
      this.keyword = "";
    }
  }
};
</script>
<style lang="scss" scoped>
@import "~@/assets/style/scss/global";
.search {
  background: color(bg);
  position: fixed;
  z-index: 999;
  top: 41px;
  left: 0;
  width: 100%;
  padding: 10px;
  box-sizing: border-box;
  line-height: 40px;
  text-align: center;
  input {
    width: 100%;
    padding: 5px;
    border-radius: 10px;
    box-sizing: border-box;
  }
}
.wrapper {
  width: 100%;
  height: 565px;
  overflow: hidden;
  position: fixed;
  top: 103px;
  left: 0;
  z-index: 999;
  background: #fff;
  .result {
    line-height: 30px;
    li {
      padding-left: 10px;
      border-bottom: 1px solid #eee;
    }
    .none {
      text-align: center;
    }
  }
}
</style>
